<template>
    <div>
      <p v-if="podMap.length == 1" class="pod-name">{{ podName }}</p>
      <el-select v-else v-model="podName" class="pod-name-select" placeholder="请选择" @change="selectPod">
        <el-option v-for="item in podMap" :key="item" :label="item" :value="item">
        </el-option>
      </el-select>
      <div class="monitoring" v-if="active == 1">
        <v-chart :option="gpuData" class="chart-item" />
        <v-chart :option="cpuData" class="chart-item" />
        <v-chart :option="memData" class="chart-item" />
      </div>
      <div class="log" v-if="active == 2">
        <ul ref="logBox" class="log-box">
          <li class="log-lis" v-for="(e, i) in logData" v-html="e" :key="i"></li>
        </ul>
      </div>
      <div class="metrics" v-if="active == 3">
        <div v-for="(e, i) in metrics" :key="i" class="metrics-item">
          <metrics-chart :option="e"  v-if="e && e.values" />
        </div>
        <div v-for="e in plots" :key="e.key" class="metrics-item">
          <metrics-chart-bar :option="e.value"  v-if="e && e.value && e.plot_type == 'bar'" />
        </div>
      </div>
    </div>
  </template>
  
  <script>
  
  import { getGameTaskVersionPodName, metricKeys, metricData } from '@/api/gameTask'
  import { usageDuration, myNamespace } from '@/api/dashboard'
  import metricsChart from '@/components/module/metrics-chart'
  import metricsChartBar from '@/components/module/metrics-chart-bar'
  
  import { formatTime } from "@/utils/tool";
  export default {
    data () {
      return {
        podName: '',
        podMap: [],
        gpuData: {},
        cpuData: {},
        memData: {},
        logSocket: null,
        logMsg: null,
        logData: [],
        metrics: [],
        plots: []
      };
    },
    props:["active"],
    components: {
      metricsChart,
      metricsChartBar
    },
    watch: {
      active(val) {
        if (val == 1) {
          this.renderMonitoring()
        }
        if (val == 2) {
          this.renderLog()
        }
        if (val == 3) {
          this.renderMetric()
        }
      }
    },
    methods: {
      async getPod() {
        let res = await getGameTaskVersionPodName({ id: this.$route.query.id })
        this.podName = res.data[0]
        this.podMap = res.data
        return
      },
      async getduration(pod_name, resource_type) {
        return await usageDuration({
          end: formatTime(new Date().getTime()),
          pod_name,
          resource_type,
          start: formatTime(new Date().getTime() - 1000 * 60 * 60 * 1),
          step: "15s",
        })
      },
      selectPod() {
        if (this.active == 1) {
          this.renderMonitoring(this.podName)
        } else if(this.active == 2) {
          this.renderLog(this.podName)        
        } else if(this.active == 3) {
          this.renderMetric()        
        }
      },
      async renderMonitoring() {
        let gpu = await this.getduration(this.podName, 'gpu')
        let cpu = await this.getduration(this.podName, 'cpu')
        let mem = await this.getduration(this.podName, 'mem')
        gpu.data.color = [
          'rgb(255, 70, 131)',
          'rgb(255, 158, 68)',
          'rgb(255, 70, 131)'
        ]
        cpu.data.color = [
          'rgb(255, 70, 131)',
          'rgb(255, 158, 68)',
          'rgb(255, 70, 131)'
        ]
        mem.data.color = [
          'rgb(255, 70, 131)',
          'rgb(255, 158, 68)',
          'rgb(255, 70, 131)'
        ]
        gpu.data.title = 'GPU'
        cpu.data.title = 'CPU'
        mem.data.title = 'MEM'
        this.gpuData = gpu.data
        this.cpuData = cpu.data
        this.memData = mem.data
      },
      toBottom () {
        let sH = this.$refs.logBox && this.$refs.logBox.scrollHeight;
        let sT = this.$refs.logBox && this.$refs.logBox.scrollTop;
        let oH = this.$refs.logBox && this.$refs.logBox.offsetHeight;
        if (sH - sT < oH + 40) {
          this.$refs.logBox.scrollTop = this.$refs.logBox.scrollHeight;
        } else {
          console.log(
            "断掉数据push，并且存储到临时容器。 当滚动条滚动到底部的时候 再把临时数据塞进正常ui"
          );
        }
      },
      msgFn(e) {
        if (e.data == "ws message received") return;
        console.log(e.data)
        if (this.logData.length > this.num * 30) {
          this.logData.shift();
          this.logData.push(e.data.replace(/\n/g, "<br />"));
        } else {
          this.logData.push(e.data.replace(/\n/g, "<br />"));
        }
        this.toBottom();
      },
      async renderLog() {
        this.logData = []
        this.logMsg && this.logMsg.disconnect();
        // ws://192.168.56.12:8081/cloud/ws/logwatch/{uid}/{namespace}/{podname}/container_name
        let res = await this.$myInfo(this)
        console.log(await myNamespace())
        let namespaceReg = await myNamespace()
        // container_name : webide || jubyter || train || serving || tensorboard     
        this.logMsg = new this.$ws({ url: `cloud/ws/logwatch/${res.id}/${ namespaceReg.data }/${this.podName}/train` })
        this.logMsg.initWebSocket(this.msgFn)
      },
      async renderMetric() {
        this.metrics = []
        let metricsKey = await metricKeys({ id: this.$route.query.id, type: 'metrics' })
        let plots = await metricKeys({ id: this.$route.query.id, type: 'plots' })
        metricsKey.data.forEach(async e => {
          let metric = await metricData({ id: this.$route.query.id, key: e, type: 'metrics' })
          this.metrics.push({
            title: e,
            values: metric.data.map(e => [e.timestamp,  e.value, e.smooth - 0])
          })
        })
        plots.data.forEach(async e => {
          let plots = await metricData({ id: this.$route.query.id, key: e, type: 'plots' })
          plots.data.forEach(e => {
            this.plots.push(e)
          })
        })
      }
    },
    async mounted() {
      await this.getPod()
      this.selectPod()
    }
  }
  </script>
  <style lang="less" scoped>
  .chart-item{
    height: 320px;
  }
  .log{
    background: #000;
    padding: 20px;
    margin: 20px 0 0;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.6);
    min-height: 400px;
    .log-box{
      overflow-x: hidden;
      overflow-y: auto;
      padding-right: 10px;
      .log-lis {
        color: #999;
        font-size: 12px;
      }
    }
  }
  .metrics{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .metrics-item{
      width: 50%;
      height: 400px;
    }
  }
  </style>